import { defineStore } from 'pinia'; // 定义容器
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes';
import { reqUserInfo } from '@/api/user';
import router from '@/router/index';
import cloneDeep from 'lodash';
import { toRaw } from 'vue';

function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
}

export const useMain = defineStore('useStore', {
  /**
   * 存储全局状态
   * 1.必须是箭头函数: 为了在服务器端渲染的时候避免交叉请求导致数据状态污染
   * 和 TS 类型推导
   */
  state: () => {
    return {
      menuRoutes: constantRoute,
      count: 0,
      list: [1, 2, 3, 4],
    };
  },
  /**
   * 用来封装计算属性 有缓存功能  类似于computed
   */
  getters: {},
  /**
   * 编辑业务逻辑  类似于methods
   */
  actions: {
    async userInfo() {
      console.log(asyncRoute[0].component);

      const res = await reqUserInfo();

      if (res.code === 200) {
        const userAsyncRoute = filterAsyncRoute(
          cloneDeep(asyncRoute),
          res.data.routes,
        );
        console.log(
          '🚀 ~ file: user.ts:47 ~ userInfo ~ userAsyncRoute:',
          userAsyncRoute,
        );
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];
        // this.asyncRouter = [...userAsyncRoute, anyRoute]

        this.menuRoutes.forEach((route: any) => {
          router.addRoute(route);
          router.options.routes.push(toRaw(route));
        });
        Window.IS_FLISH = true;
        console.log(constantRoute[0].component);
        console.log(asyncRoute[0].component);
        console.log(JSON.parse(JSON.stringify(asyncRoute[0])));

        return 'ok';
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
  },
  persist: {
    enabled: true,
  },
});
